package cn.zniot.so.application;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 连接会话管理器，负责管理所有的连接会话映射表
 */
public class SessionManager {
	private static Logger logger = Logger.getLogger(SessionManager.class);

	/**
	 * 会话单例
	 */
	private static SessionManager instance = new SessionManager();

	private SessionManager() {
	}

	public static SessionManager getInstance() {
		return instance;
	}

	/**
	 * 车机会话映射表
	 * key:盒子与服务器通信时使用的IP和端口
	 * value:通信session引用
	 */
	private ConcurrentHashMap<String, IoSession> mdMap_tcp = new ConcurrentHashMap<String, IoSession>();
	

	/**
	 * 在指定会话表上注册会话,从session中取得ip和端口
	 * @param ipAndPort
	 * @param session
	 * @return
	 */
	public boolean register_tcp(String ipAndPort, IoSession session) {
		boolean result = true;
		this.mdMap_tcp.put(ipAndPort, session);
		return result;
	}

	/**
	 * 在指定会话表上取消会话注册
	 */
	public boolean unregister(String ipAndPort) {
		boolean result = true;
		if (!this.mdMap_tcp.containsKey(ipAndPort)) {
		    if (logger.isDebugEnabled()) {
		        logger.warn("ipAndPort:" + ipAndPort + " had not been registered...");
            }
		} else {
			this.mdMap_tcp.remove(ipAndPort);
		}
		return result;
	}

	/**
	 * 在指定会话表上查找会话
	 */
	public IoSession getSession(String ipAndPort) {
		if (this.mdMap_tcp == null) {
		    if (logger.isDebugEnabled()) {
		        logger.warn("session map has not been initiative...");
		    }
			return null;
		}
		return mdMap_tcp.get(ipAndPort);
//		Set<String> set = this.mdMap_tcp.keySet();
//		if(set != null){
//			Iterator<String> it = set.iterator();
//			while(it.hasNext()){
//				return this.mdMap_tcp.get(it.next());
//			}
//			return null;
//		} else return null;
	}

	/**
	 * 获取指定会话表的大小
	 */
	public int getSize() {
		if (this.mdMap_tcp == null) {
		    if (logger.isDebugEnabled()) {
		        logger.warn("session map has not been initiative...");
		    }
			return -1;
		}
		return this.mdMap_tcp.size();
	}
	
	/**
	 * 获取所有的盒子session
	 */
	public Collection<IoSession> getAllSessions(){
		return this.mdMap_tcp.values();
	}

	public synchronized String getIpPortByIosession(IoSession ioSession) {
        if (this.mdMap_tcp.size() > 0) {
            for (String IpAndPort : this.mdMap_tcp.keySet()) {
                if (this.mdMap_tcp.get(IpAndPort).equals(ioSession)) {
                    return (String) IpAndPort;
                }
            }
        }
        return null;
    }
}
